const fs = require('fs')
const path = require('path')
const { spawn, exec } = require('child_process')

exports.buildHelpTemplate = (helpValue) => {
    let str = '\n'
    for (let row of helpValue) {
        str += `${row[0]}\t\t${row[1]}\n`
    }
    return str
}

exports.buildPromptListTemplate = (pageList = [], subpackages = []) => {
    const promptList = []

    if (pageList && pageList.length) {
        promptList.push({
            type: 'checkbox',
            message: '选择需要编译的页面:',
            name: 'pages',
            choices: [...pageList]
        })
    }

    if (subpackages && subpackages.length) {
        promptList.push({
            type: 'checkbox',
            message: '选择需要编译的分包:',
            name: 'subpackages',
            choices: subpackages.map(v => { return v.root })
        })
    }

    return promptList
}

exports.readFile = (filePath, parseJson = false) => {
    if (!filePath) {
        return ''
    }
    let str = fs.readFileSync(filePath, { encoding: 'UTF-8' })
    if (parseJson) {
        try {
            return JSON.parse(str)
        } catch (e) {
            return str
        }
    }
    return str
}

exports.writeFile = (filePath, text = '') => {
    if (filePath) {
        let dirPath = path.resolve(filePath, '../')
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath)
        }
        fs.writeFileSync(filePath, text)

    }
}

exports.runShell = (command, args, output = false) => {
    const platform = process.platform

    return new Promise((reslove, reject) => {
        if(platform == 'win32') {
            let cmd = command + ' ' + [...args].join(' ')
            const execRes = exec(cmd, {
                encoding: 'UTF-8'
            })
            if (output) {
                execRes.stdout.on('data', (data) => {
                    console.log(`${data}\n`)
                })
                execRes.stderr.on('data', (data) => {
                    console.log(`${data}\n`)
                })
            }
            execRes.on('close', (code) => {
                reslove(code)
            })
            execRes.on('error', (err) => {
                reject(err)
            })
        } else {
            const execRes = spawn(command, [...args], {
                encoding: 'UTF-8'
            })
            if (output) {
                execRes.stdout.on('data', (data) => {
                    console.log(`${data}\n`)
                })
                execRes.stderr.on('data', (data) => {
                    console.log(`${data}\n`)
                })
            }
            execRes.on('close', (code) => {
                reslove(code)
            })
            execRes.on('error', (err) => {
                reject(err)
            })
        }        
    })
}

exports.ignoreJsonBuilder = (ignorePages = [], ignoreSubpackage = []) => {
    let resultArr = []
    // ignorePages.reduce((x, y, i) => { console.log(x, '|', y, '|', i); return (i <= 1 ? `'${x}'` : x) + `,'${y}'` })
    if (Array.isArray(ignorePages)) {
        for (let pagePath of ignorePages) {
            let pathSplit = pagePath.split('/')
            pathSplit.unshift('./src')
            pathSplit.splice(pathSplit.length - 1, 1, '*')
            resultArr.push(pathSplit.join('/'))
        }
    }
    if (Array.isArray(ignoreSubpackage)) {
        for (let pagePath of ignoreSubpackage) {
            let pathSplit = pagePath.split('/')
            pathSplit.unshift('./src')
            pathSplit.push('**')
            resultArr.push(pathSplit.join('/'))
        }
    }
    return resultArr
}